﻿using Architecture.Domain.Dto.UserInfoDto;
using Architecture.Domain.Dto.UserInfoRoleDto;
using Architecture.Repository.Interface;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace Architecture.Domain.Service.UserInfoServices
{
    public class UserInfoService : IUserInfoService
    {
        /// <summary>
        /// 用户信息仓储
        /// </summary>
        protected readonly IUserInfoRepository _userInfoRepository;

        /// <summary>
        /// 省信息仓储
        /// </summary>
        protected readonly IProvinceRepository _provinceRepository;

        /// <summary>
        /// 市信息仓储
        /// </summary>
        protected readonly ICityRepository _cityRepository;

        /// <summary>
        /// 县信息仓储
        /// </summary>
        protected readonly ICountryRepository _courierRepository;

        /// <summary>
        ///  用户信息角色服务
        /// </summary>
        protected readonly IUserInfoRoleRepository _userInfoRoleRepository;

        /// <summary>
        /// 角色仓储
        /// </summary>
        protected readonly IRoleRepository _roleRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="userInfoRepository">用户信息仓储</param>
        /// <param name="provinceRepository">省信息仓储</param>
        /// <param name="cityRepository">市信息仓储</param>
        /// <param name="courierRepository">县信息仓储</param>
        /// <param name="roleRepository">角色仓储</param>
        /// <param name="userInfoRoleRepository">用户信息角色服务</param>
        public UserInfoService(IUserInfoRepository userInfoRepository, IProvinceRepository provinceRepository, ICityRepository cityRepository, ICountryRepository courierRepository, IRoleRepository roleRepository, IUserInfoRoleRepository userInfoRoleRepository)
        {
            _userInfoRepository = userInfoRepository;
            _provinceRepository = provinceRepository;
            _cityRepository = cityRepository;
            _courierRepository = courierRepository;
            _roleRepository = roleRepository;
            _userInfoRoleRepository = userInfoRoleRepository;
        }

        /// <summary>
        /// 添加用户信息
        /// </summary>
        /// <param name="userInfo">用户实体</param>
        /// <returns>返回受影响的行数</returns>
        public async Task<int> AddAsync(UserInfo userInfo)
        {

            userInfo.CreatedBy = userInfo.UserName;
            userInfo.CreatedDate = DateTime.Now;
            userInfo.UserPwd = "12345678";
            return await _userInfoRepository.AddAsync(userInfo);
        }

        /// <summary>
        /// 修改用户信息
        /// </summary>
        /// <param name="userId">用户主键</param>
        /// <returns>返回受影响的行数</returns>
        public async Task<int> UpdateAsync(int userId)
        {
            var res = await _userInfoRepository.GetModelAsync(userId);
            if (res != null)
            {
                res.UpdatedBy = res.UserName;
                res.UpdatedDate = DateTime.Now;
                return await _userInfoRepository.UpdateAsync(res);
            }
            else
            {
                return -1;
            }
        }

        /// <summary>
        /// 删除用户信息
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>返回受影响的行数</returns>
        public async Task<int> DeletedAsync(int userId)
        {
            var res = await _userInfoRepository.GetModelAsync(userId);
            if (res != null)
            {
                res.IsDeleted = true;
                res.DeletedBy = res.UserName;
                res.DeletedDate = DateTime.Now;
                return await _userInfoRepository.UpdateAsync(res);
            }
            else
            {
                return -1;
            }
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <returns>返回用户信息列表</returns>
        public async Task<PageUserInfoDto<UserInfoDto>> GetUserInfoDto(int PageIndex, int PageSize, string? UserName)
        {
            var paging = new PageUserInfoDto<UserInfoDto>();
            var res = await _userInfoRoleRepository.GetAllAsync();
            var result = await _roleRepository.GetAllAsync();

            var list = (from a in await _userInfoRepository.GetAllAsync()
                        join
                        b in await _provinceRepository.GetAllAsync()
                        on a.ProvinceId equals b.ProvinceId
                        join c in await _cityRepository.GetAllAsync()
                        on a.CityId equals c.CityId
                        join d in await _courierRepository.GetAllAsync()
                        on a.CountyId equals d.CountyId
                        where !a.IsDeleted
                        //group f.RoleName by a.UserId into g  
                        select new UserInfoDto
                        {
                            UserId = a.UserId,
                            UserName = a.UserName,
                            Gender = a.Gender,
                            ProvinceId = a.ProvinceId,
                            CityId = a.CityId,
                            CountyId = a.CountyId,
                            Address = a.Address,
                            CreatedBy = a.CreatedBy,
                            CreatedDate = a.CreatedDate,
                            UpdatedBy = a.UpdatedBy,
                            UpdatedDate = a.UpdatedDate,
                            ProvinceName = b.ProvinceName,
                            CityName = c.CityName,
                            CountyName = d.CountyName,
                            roleName = (from e in res
                                        join f in result on e.RoleId equals f.RoleId
                                        where e.UserId == a.UserId && !e.IsDeleted && !f.IsDeleted
                                        select new GetRoleNameDto
                                        {
                                            RoleName = f.RoleName
                                        }).ToList()
                        }).ToList();
            if (!string.IsNullOrEmpty(UserName))
            {
                list = list.Where(x => x.UserName.Contains(UserName)).ToList();
            }
            paging.totalCount = list.Count;
            paging.pageCount = (int)Math.Ceiling(list.Count * 1.0 / PageSize);
            paging.list = list.OrderByDescending(x => x.CreatedDate).Skip((PageIndex - 1) * PageSize).Take(PageSize).ToList();
            return paging;
        }

        /// <summary>
        /// 获取用户信息(用户ID,用户名称)
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<List<UserInfoDtoTwo>> GetALLInfoAsyncTwo(string ids)
        {
            var list = from a in await _userInfoRepository.GetAllAsync()
                       where a.IsDeleted == false && ids.Contains(a.DepartmentId.ToString())
                       select new UserInfoDtoTwo
                       {
                           id = a.UserId,
                           label = a.UserName,
                       };
            return list.ToList();
        }

        /// <summary>
        /// 条件查询用户信息
        /// </summary>
        /// <param name="userName">用户名称</param>
        /// <returns>返回用户信息列表</returns>
        public async Task<List<UserInfo>> GetAllAsync(string userName)
        {
            return await _userInfoRepository.GetAsync(x => x.UserName == userName);
        }

        /// <summary>
        /// 反填用户信息
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <returns>反填用户信息</returns>
        public async Task<UserInfo> GetModelAsync(int id)
        {
            return await _userInfoRepository.GetModelAsync(id);
        }

        /// <summary>
        /// 获取用户信息列表
        /// </summary>
        /// <returns>返回用户信息列表</returns>
        public async Task<List<UserInfo>> GetListAsync()
        {
            return await _userInfoRepository.GetAllAsync();
        }

        /// <summary>
        /// 修改用户信息
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public async Task<int> UpdateUserInfoAsync(UserInfo userInfo)
        {
            userInfo.UpdatedBy = userInfo.UserName;
            userInfo.UpdatedDate = DateTime.Now;
            return await _userInfoRepository.UpdateAsync(userInfo);
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="UserName">用户名</param>
        /// <param name="UserPwd">密码</param>
        /// <returns>返回受影响的行数</returns>
        public async Task<UserInfoRoleInfoDto> UserInfoLogin(string UserName, string UserPwd)
        {
            var res = (from a in await _userInfoRepository.GetAllAsync()
                      join b in await _userInfoRoleRepository.GetAllAsync()
                      on a.UserId equals b.UserId
                      join c in await _roleRepository.GetAllAsync()
                      on b.RoleId equals c.RoleId
                      where a.UserName == UserName && a.UserPwd == UserPwd && !a.IsDeleted && !b.IsDeleted && !c.IsDeleted
                      select new UserInfoRoleInfoDto
                      {
                          UserId = a.UserId,
                          UserName = a.UserName,
                          Gender = a.Gender,
                          ProvinceId = a.ProvinceId,
                          CityId = a.CityId,
                          CountyId = a.CountyId,
                          Address = a.Address,
                          UserInfoRoleId = b.UserInfoRoleId,
                          RoleId = c.RoleId.ToString(),
                          RoleName = c.RoleName,
                      });
            return res.FirstOrDefault();

        }
    }
}
